#! /bin/bash

#################################################
# mvflash: move flash file from /tmp directory
#          to $HOME directory 
# author : junix<unix_jun@yahoo.com.cn>
# date   :  2009年 09月 24日 星期四 23:52:31 CST
#################################################


TMP='/tmp'
PREFIX='Flash'
DEFAULT_SLEEP_TIME=10
dirname=

mvflash() {
	if ls ${TMP}/${PREFIX}* 1>/dev/null 2>&1
	then
		#mv ${PREFIX}* $HOME
		index=1
		for file in $(ls -rt ${TMP}/${PREFIX}* 2>/dev/null)
		do
			#echo $file
			filename=`date +%F-%S`
			if [ -e ${dirname:-${HOME}}/${filename} ]; then
				filename="${filename}"-"${index}"
				let "index = $index + 1 "
				#echo $index
			fi

			mv ${file} "${dirname:-${HOME}}"/"${filename}" 2>/dev/null
		done
	fi
}


while getopts hvt:d: OPTION 2>/dev/null
do
	case $OPTION in
		h )
			echo -e "Usage: `basename $0` [-t seconds][-h][-v][-d directory]"
			echo -e "		-t time to sleep "
			echo -e "		-d directory to store the flies"
			echo -e "		-h help infomation"
			echo -e "		-v version"
			exit 1
			;;
		v )
			echo -e "mvflash 0.01"
			echo -e "a shell script to mv flash file from /tmp to your home directory"
			echo -e "author: junix<unix_jun@yahoo.com.cn>"
			exit 0
			;;
		t )
			stime=$(($OPTARG+1))
			if [ ${stime} -gt ${DEFAULT_SLEEP_TIME} ];then
				DEFAULT_SLEEP_TIME=$((--stime))
				echo "sleep time: ${DEFAULT_SLEEP_TIME}"
			fi
			;;
		d )
            dirname=${OPTARG}
            if [ ! -d $dirname ]; then
				echo "${dirname}: No such directory"
				exit 1
			fi

            if [ ! -w $dirname ]; then
				echo "${dirname}: Can not write"
				exit 1
			fi
			;;
		* )
			echo "Error:try `basename $0` -h for some help infomation"
			exit 1
			;;
	esac
done


while true
do
	mvflash
	sleep ${DEFAULT_SLEEP_TIME}
done

